<template>
  <div>
    <div class="flex flex-row justify-between w-full px-4 pt-4 pb-2">
      <div class="cursor-pointer" @click="onCancel">取消</div>
      <div class="text-yxt-blue cursor-pointer" @click="onConfirm">完成</div>
    </div>

    <div class="flex flex-row items-center w-full justify-between py-8 px-6">
      <div
        :class="`w-[150px] ${index === 0 ? 'active-text' : ''} cursor-pointer`"
        @click="onClickDate(0)"
      >
        <div v-if="_startDate" :class="`flex flex-col items-center }`">
          <div class="text-lg font-bold">{{ cp_startTimeStr }}</div>
          <div>{{ cp_startDateStr }}</div>
        </div>
        <div v-else>开始日期时间</div>
      </div>

      <van-icon
        name="down"
        size="24"
        :color="errorDes.length > 0 ? '#ff4949' : '#909399'"
        class="transform -rotate-90"
      />

      <div
        :class="`ml-7 w-[150px] ${index === 1 ? 'active-text' : ''} cursor-pointer`"
        @click="onClickDate(1)"
      >
        <div v-if="_endDate" :class="`flex flex-col items-center}`">
          <div class="text-lg font-bold">{{ cp_endTimeStr }}</div>
          <div>{{ cp_endDateStr }}</div>
        </div>
        <div v-else>结束日期时间</div>
      </div>
    </div>

    <van-picker-group :show-toolbar="false" :tabs="['选择日期', '选择时间']">
      <van-date-picker
        v-model="cp_currentDate"
        :min-date="new Date()"
        :max-date="maxDate"
        :formatter="formatter"
      />
      <van-time-picker v-model="cp_currentTime" :filter="startTimeFilter" />
    </van-picker-group>
  </div>
</template>

<script setup>
// 时间统一使用'YYYY-MM-DD HH:mm'标准
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import { ref, computed, defineProps, defineEmits, watch, watchEffect } from "vue";
import { showToast } from "vant";

const FORMDATE = "YYYY-MM-DD HH:mm";
dayjs.extend(customParseFormat);

let maxDate = new Date();
// 增加 6 个月
maxDate.setMonth(maxDate.getMonth() + 6);

const emits = defineEmits(["update:show", "update:editIndex", "onConfirm", "onCancel"]);
const props = defineProps({
  startDate: {
    type: String,
    required: true,
  },
  endDate: {
    type: String,
    required: true,
  },
  editIndex: {
    type: Number,
    default: 0,
  },
});

const show = ref(false);
const cp_show = computed({
  set(v) {
    emits("update:show", v);
  },
  get() {
    return show;
  },
});

const index = ref(props.editIndex);
const groupIndex = ref(0);

function onClickDate(tempIndex) {
  index.value = tempIndex;
  emits("update:editIndex", index);
}

function formatter(type, option) {
  if (type === "year") {
    option.text += "年";
  }
  if (type === "month") {
    option.text += "月";
  }
  if (type === "day") {
    option.text += "号";
  }
  return option;
}

function startTimeFilter(type, option) {
  // 分钟间隔格式为5分钟
  if (type === "minute") {
    return option.filter((option) => Number(option.value) % 5 === 0);
  }
  return option;
}

const _startDate = ref(props.startDate);
const _endDate = ref(props.endDate);

const startDateObj = computed(() =>
  _startDate.value ? dayjs(_startDate.value, FORMDATE) : dayjs()
);
const endDateObj = computed(() =>
  _endDate.value ? dayjs(_endDate.value, FORMDATE) : dayjs().add(1, "hour")
);

const errorDes = ref("");
watchEffect(() => {
  const diff = endDateObj.value.diff(startDateObj.value, "minute");
  const minDur = 15;
  if (diff < minDur && diff > 0) {
    errorDes.value = `持续时间小于${minDur}分钟`;
    return;
  }
  errorDes.value = "";
});

console.log("startDateObj:", startDateObj.value.format(FORMDATE));

const cp_startDateStr = computed(() => startDateObj.value.format("YYYY-MM-DD"));
const cp_startTimeStr = computed(() => startDateObj.value.format("HH:mm"));
const cp_endDateStr = computed(() => endDateObj.value.format("YYYY-MM-DD"));
const cp_endTimeStr = computed(() => endDateObj.value.format("HH:mm"));

const cp_currentDate = computed({
  set(v) {
    var targeDayObj = index.value === 0 ? startDateObj.value : endDateObj.value;
    targeDayObj = targeDayObj.year(v[0]);
    targeDayObj = targeDayObj.month(Math.max(Math.min(v[1] - 1, 11), 0));
    targeDayObj = targeDayObj.date(v[2]);
    if (index.value === 0) {
      _startDate.value = targeDayObj;
    } else {
      _endDate.value = targeDayObj;
    }
  },

  get() {
    return index.value == 0
      ? cp_startDateStr.value.split("-")
      : cp_endDateStr.value.split("-");
  },
});

// 监听开始时间变化
watch(_startDate, (newVal) => {
  if (!newVal) return;
  // 检查是否早于当前时间
  if (dayjs(newVal).isBefore(dayjs())) {
    showToast("预约时间不能早于当前时间");
    return;
  }
  // 自动设置结束时间为开始时间后1小时
  _endDate.value = dayjs(newVal).add(1, "hour").format("YYYY-MM-DD HH:mm:ss");
});

const cp_currentTime = computed({
  set(v) {
    var targeDayObj = index.value === 0 ? startDateObj.value : endDateObj.value;
    targeDayObj = targeDayObj.hour(v[0]);
    targeDayObj = targeDayObj.minute(v[1]);
    if (index.value === 0) {
      _startDate.value = targeDayObj;
    } else {
      _endDate.value = targeDayObj;
    }
  },

  get() {
    return index.value == 0
      ? cp_startTimeStr.value.split(":")
      : cp_endTimeStr.value.split(":");
  },
});

function onConfirm() {
  if (errorDes.value) {
    showToast(errorDes.value);
    return;
  }
  if (dayjs(startDateObj.value).isBefore(dayjs())) {
    showToast("预约时间不能早于当前时间");
    return;
  }

  const diff = endDateObj.value.diff(startDateObj.value, "minute");
  if (diff < 0) {
    // 开启时间 大于 结束时间 将开始时间设置为红色
    errorDes.value = "结束时间早于开始时间";
    showToast(errorDes.value);
    return;
  }
  emits(
    "onConfirm",
    startDateObj.value.format(FORMDATE),
    endDateObj.value.format(FORMDATE)
  );
}

function onCancel() {
  emits("onCancel");
}
</script>

<style lang="less" scoped>
.active-text {
  color: #436bff;
}
</style>
